import { CloseOutlined } from '@ant-design/icons';
import { useRafInterval } from 'ahooks';
import {
  Button,
  Progress,
  Space,
  Table,
  Pagination,
  Tooltip,
  message,
  Splitter,
  TableProps,
  Badge,
} from 'antd';
import { ColumnsType } from 'antd/es/table';
import { TableRowSelection } from 'antd/es/table/interface';
import { CSSProperties, useEffect, useMemo, useState } from 'react';
import { useSearchParams } from 'react-router-dom';

import datasetService from '@/api/services/datasetService';
import { UploadFileCollection } from '@/common';
import { Iconify, SvgIcon } from '@/components/icon';
import ConfirmModal from '@/pages/datasets/components/DeleteConfirmModal';
import { useSettings } from '@/store/settingStore';
import { useThemeToken } from '@/theme/hooks';
import { ThemeMode } from '@/types/enum';
import type { MenuProps } from 'antd';

import type { TableColumnsType } from 'antd';


import useWindowWidth from '@/hooks/event/use-window-width';

type Props = {
  datas: UploadFileCollection[];
  onDelete: (collection: UploadFileCollection, isArr: boolean) => void;
  onUpdate?: (uid: string, isResume: boolean) => void;
} & TableProps;
export default function UrlFileListTable({ datas, onDelete, onUpdate, className }: Props) {
  const { themeMode } = useSettings();
  const { colorPrimary, colorSuccess, colorBgBase, colorBgLayout } = useThemeToken();
  const [expandDataSource, setExpandDataSource] = useState([]);
  const [recordId, setRecordId] = useState('');
  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [dataTotal, setDatatotal] = useState(0);
  const [isExpanded, setIsExpanded] = useState(false);

  const [showConfirmResume, setShowConfirmResume] = useState(false);
  const [showConfirmStop, setShowConfirmStop] = useState(false);
  const [recordTarget, setRecordTarget] = useState(null);
  const [searchParams] = useSearchParams();
  const id = searchParams.get('id');
  const { windowWidth, isPc } = useWindowWidth();

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [showDel, setShowDel] = useState(false);

  const [tableParams, setTableParams] = useState<TableParams>({
    pagination: {
      current: 1,
      pageSize: 2,
    },
  });

  const handleTableChange: TableProps<DataType>['onChange'] = (pagination) => {
    console.log(pagination);

    setTableParams({
      pagination,
    });

    // `dataSource` is useless since `pageSize` changed
    // if (pagination.pageSize !== tableParams.pagination?.pageSize) {
    //   setData([]);
    // }
  };

  useEffect(() => {
    console.log(datas);
    // 将数组转换为 Set
    const validUids = new Set(datas.map((item) => item.uid));

    setSelectedRowKeys((prev) => {
      // 使用 Set 的 has 方法
      const filtered = prev.filter((key) => validUids.has(key));
      return filtered.length === prev.length ? prev : filtered;
    });
  }, [datas]);

  interface ExpandedDataType {
    key: React.Key;
    submitTime: string;
    link: string;
    status: string;
  }

  const onRefresh = async (record?) => {
    // setRecordTarget(record)
    // setShowConfirmResume(true)

    if (selectedRowKeys && selectedRowKeys.length > 0) {
      const deletePromises = selectedRowKeys.map((uid) => {
        console.log(uid);

        return datasetService.weburlTaskResume(uid); // 返回每个删除请求的 Promise
      });

      // 使用 Promise.all 并行处理所有删除请求
      Promise.all(deletePromises).then((results) => {
        console.log('重启', results);
        setShowDel(false);
        selectedRowKeys.map((uid) => {
          onUpdate && onUpdate(uid, true);
        });

        message.success('任务重启成功');
        setSelectedRowKeys([]);
      });
    } else {
      await datasetService.weburlTaskResume(record.uid);
      onUpdate && onUpdate(record.uid, true);
      message.success('任务重启成功');
    }
  };

  const onStop = async (record) => {
    // setRecordTarget(record)
    // setShowConfirmStop(true)

    if (selectedRowKeys && selectedRowKeys.length > 0) {
      const deletePromises = selectedRowKeys.map((uid) => {
        console.log(uid);

        return datasetService.weburlTaskStop(uid); // 返回每个删除请求的 Promise
      });

      // 使用 Promise.all 并行处理所有删除请求
      Promise.all(deletePromises).then((results) => {
        console.log('停止', results);
        setShowDel(false);
        selectedRowKeys.map((uid) => {
          onUpdate && onUpdate(uid, true);
        });

        message.success('任务暂停成功');
        setSelectedRowKeys([]);
      });
    } else {
      await datasetService.weburlTaskStop(record.uid);
      onUpdate && onUpdate(record.uid, false);
      message.success('任务暂停成功');
    }
  };

  const iconMap = {
    md: <SvgIcon size="18" icon="ic_file_md" />,
    txt: <SvgIcon size="18" icon="ic_file_txt" />,
    pdf: <SvgIcon size="18" icon="ic_file_pdf" />,
    ppt: <SvgIcon size="18" icon="ic_file_ppt" />,
    pptx: <SvgIcon size="18" icon="ic_file_ppt" />,
    xls: <SvgIcon size="18" icon="ic_file_excel" />,
    xlsx: <SvgIcon size="18" icon="ic_file_excel" />,
    doc: <SvgIcon size="18" icon="ic_file_word" />,
    docx: <SvgIcon size="18" icon="ic_file_word" />,
    file: <SvgIcon size="18" icon="ic_file" />,
    url: <SvgIcon size="18" icon="ic_file" />,
  };

  const getSize = (size: number) => {
    if (size >= 1024 * 1024 * 1024) {
      return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`;
    }
    if (size >= 1024 * 1024) {
      return `${(size / (1024 * 1024)).toFixed(2)} MB`;
    }
    if (size >= 1024) {
      return `${(size / 1024).toFixed(2)} KB`;
    }
    if (size == 0) {
      return ``;
    }
    return `${size} B`;
  };

  // 获取文件名后缀
  const getFileIcon = (name: string) => {
    try {
      const arr = name.split('.');
      return iconMap[arr[arr.length - 1]];
    } catch {
      return iconMap.file;
    }
  };

  const columns: ColumnsType<UploadFileCollection> = [
    {
      title: '链接',
      dataIndex: 'name',
      width: '50%',
      ellipsis: true,
      // render: (_, record) => (
      //   <div className="flex items-center">
      //     {/* <img src={record.avatar} alt="" className="h-9 w-9 rounded-full" /> */}
      //     {getFileIcon(record.name)}
      //     <div className="ml-2 flex flex-col">
      //       <span className="font-semibold">{record.name}</span>
      //       {/* <span className="text-xs opacity-50">{record.createTime}</span> */}
      //     </div>
      //   </div>
      // ),
    },
    // {
    //   title: '文件大小',
    //   dataIndex: 'status',
    //   render: (_, record) => (
    //     <div>{getSize(record.size)}</div>
    //   ),
    // },
    {
      title: '状态',
      dataIndex: 'status',
      width: '50%',
      render: (_, record) => (
        <div>
          {
            record.status === 'ready' || record?.percent == 0 ? (
              record?.type === 'url' ? (
                <span style={{ color: '#86909C' }}>等待导入</span>
              ) : (
                <span style={{ color: '#86909C' }}>等待上传</span>
              )
            ) : record.status === 'error' ? (
              <span className="text-error">{record?.type === 'url' ? '导入失败' : '上传失败'}</span>
            ) : record.status === 'revoked' ? (
              <div style={{ display: 'flex' }}>
                <span style={{ color: '#6640FF', width: '100px' }}>任务暂停</span>
                {/* <Progress
                  percent={record?.percent}
                  strokeColor={{ from: colorPrimary, to: colorSuccess }}
                  trailColor="transparent"
                  status="active"
                /> */}
              </div>
            ) : (
              <Progress
                percent={record?.percent}
                strokeColor={{ from: colorPrimary, to: '#00D0FE' }}
                trailColor="transparent"
                status="active"
              />
            )

            // <div style={{display: 'flex'}}>
            //   <span style={{color: '#6640FF', width: '200px'}}>
            //     {record?.statusCn}
            //     {isPc && record?.totalCount != 0 && record?.successCount != 0  && <span style={{color: '#6640FF', width: '100px'}}>({record?.successCount}/{record?.totalCount})</span> }
            //   </span>
            //   <Progress percent={record?.percent} strokeColor={{ from: colorPrimary, to: colorSuccess }} trailColor="transparent" status="active" />
            // </div>
          }
        </div>
      ),
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: isPc ? '160px' : '120px',
      render: (_, record) => (
        <div className="flex items-center space-x-2">
          <Tooltip title="删除" placement="bottom">
            <Button
              shape="circle"
              danger
              type="text"
              style={{ border: 'none' }}
              disabled={record.task_src == 'data_connector' && record.status != 'error'}
              onClick={() => {
                console.log('record================', record);
                onDelete(record);
              }}
            >
              <SvgIcon icon="delete-icons" size={16} />
              删除
            </Button>
          </Tooltip>
          {record.status === 'uploading' && (
            <Tooltip title="暂停">
              <Button
                shape="circle"
                type="text"
                style={{ border: 'none' }}
                disabled={record.task_src == 'data_connector' && record.status != 'error'}
                onClick={() => {
                  onStop(record);
                }}
              >
                <SvgIcon icon="pause-icons" size={16} />
                暂停
              </Button>
            </Tooltip>
          )}
          {(record.status === 'error' || record.status === 'revoked') && (
            <Tooltip title="重试">
              <Button
                shape="circle"
                style={{ border: 'none' }}
                disabled={record.task_src == 'data_connector'}
                onClick={() => {
                  onRefresh(record);
                }}
              >
                <SvgIcon icon="retry-icons" size={16} />
                重试
              </Button>
            </Tooltip>
          )}
        </div>
      ),
    },
  ];

  const expandColumns: TableColumnsType<ExpandedDataType> = [
    { title: '链接', dataIndex: 'link', key: 'link', width: '100%', ellipsis: true },
    // { title: '备注', dataIndex: 'traceback', key: 'traceback' },
    {
      title: '状态',
      key: 'status',
      width: 150,
      render: (record) =>
        record.status == 'SUCCESS' ? (
          <Badge status="success" text={record.status_cn} />
        ) : record.status == 'FAILURE' ? (
          <Badge status="error" text={record.status_cn} />
        ) : record.status == 'REVOKED' ? (
          <Badge status="default" text={record.status_cn} />
        ) : (
          <Badge status="processing" text={record.status_cn} />
        ),
    },
    { title: '时间', dataIndex: 'submitTime', key: 'submitTime', width: 150, hidden: !isPc },
  ];

  const style: CSSProperties = {
    height: '100%',
    padding: '16px',
    borderRadius: '16px',
    backgroundColor: themeMode === ThemeMode.Light ? colorBgLayout : 'rgba(145, 158, 171, 0.12)',
  };

  const fetchChildUrl = async () => {
    const data = await datasetService.getWeburlChildStatus(recordId, pageNum, pageSize);
    console.log(data);
    if (data && !Array.isArray(data.page_data)) {
      return;
    }
    setExpandDataSource(data.page_data);
    setDatatotal(data.total_cnt);
    if (pageNum > data.page_cnt) {
      setPageNum(data.page_cnt);
    }
  };

  const defaultConfig = () => {
    setExpandDataSource([]);
    setDatatotal(0);
    setPageNum(1);
    setPageSize(10);
  };

  const [expandedRowKeys, setExpandedRowKeys] = useState<React.Key[]>([]);
  const handleExpand = (expanded: boolean, record) => {
    console.log(expanded, record);
    if (expanded) {
      if (record?.uid) {
        defaultConfig();
        setRecordId(record.uid);
        setIsExpanded(true);
        setExpandedRowKeys([record.uid]);
      }
    } else {
      setRecordId('');
      setIsExpanded(false);
      setExpandedRowKeys([]);
    }
  };

  useRafInterval(() => {
    if (isExpanded && recordId) {
      fetchChildUrl();
    }
  }, 4000);

  useEffect(() => {
    if (recordId) {
      fetchChildUrl();
    }
  }, [recordId, pageNum, pageSize]);

  const expandedRowRender = () => (
    <div className="my-1 ml-20">
      <Table<ExpandedDataType>
        columns={expandColumns}
        dataSource={expandDataSource}
        pagination={false}
        rowKey="link"
      />
      <Pagination
        style={{ paddingTop: '10px', justifyContent: 'end' }}
        current={pageNum}
        pageSize={pageSize}
        total={dataTotal}
        showSizeChanger
        onChange={(page, pageSize) => {
          setPageNum(page);
          setPageSize(pageSize);
        }}
      // showTotal={(total, range) => `${range[0]}-${range[1]} of ${total}`}
      />
    </div>
  );

  // const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
  //   console.log('selectedRowKeys changed: ', newSelectedRowKeys);
  //   setSelectedRowKeys(newSelectedRowKeys);
  // };

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);

    // 1. 先过滤掉不符合条件的记录
    const filteredData = datas.filter(
      (record) => !(record.task_src == 'data_connector' && record.status != 'error'),
    );

    console.log('11111111111111', filteredData);
    const arr = filteredData.map((item) => item.fileId);

    // 2. 从过滤后的数据中获取fileId数组
    const validFileIds = filteredData.map((item) => item.fileId);

    setSelectedRowKeys(arr);
    // 3. 只保留newSelectedRowKeys中存在于validFileIds的项
    const filteredSelectedKeys = newSelectedRowKeys.filter((key) =>
      validFileIds.includes(key as string),
    );

    console.log('Filtered selected keys:', filteredSelectedKeys);
    setSelectedRowKeys(filteredSelectedKeys);
  };

  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const selectedItems = useMemo(() => {
    // 创建哈希映射提升查找效率
    const dataMap = new Map(datas.map((item) => [item.uid, item]));

    return selectedRowKeys
      .map((uid) => dataMap.get(uid)) // O(1) 查找
      .filter((item): item is DataType => !!item); // 类型守卫过滤undefined
  }, [datas, selectedRowKeys]);

  return (
    <>
      <ConfirmModal
        visible={showConfirmResume}
        text="确定要重启任务吗？"
        onCancel={() => setShowConfirmResume(false)}
        onConfirm={() => {
          if (recordTarget?.uid) {
            return;
          }
          datasetService.weburlTaskResume(recordTarget?.uid);
          message.success('任务重启成功');
        }}
      />
      <ConfirmModal
        visible={showConfirmStop}
        text="确定要暂停任务吗？"
        onCancel={() => setShowConfirmStop(false)}
        onConfirm={() => {
          if (recordTarget?.uid) {
            return;
          }
          datasetService.weburlTaskStop(recordTarget?.uid);
          message.success('任务暂停成功');
        }}
      />
      <Table
        rootClassName="rounded-e-md"
        bordered={false}
        // showHeader={false}
        size="small"
        className={className}
        rowKey="uid"
        columns={columns}
        rowSelection={{ ...rowSelection }}
        expandable={{
          onExpand: handleExpand,
          expandedRowKeys,
          expandedRowRender,
          defaultExpandedRowKeys: ['0'],
        }}
        dataSource={datas}
        pagination={false}
      // pagination={tableParams.pagination}
      // onChange={handleTableChange}
      />

      {selectedRowKeys.length > 0 && (
        <div
          className="animated-div"
          style={{
            position: 'fixed',
            bottom: '5%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            background: '#474C5F',
            borderRadius: '50px',
          }}
        >
          <Space className="ml-2 mr-2" style={{ height: '45px' }}>
            <Button
              style={{ color: '#fff' }}
              type="text"
              icon={<CloseOutlined />}
              onClick={() => {
                setSelectedRowKeys([]);
                setShowDel(false);
              }}
            />
            <span className="whitespace-nowrap text-nowrap text-xs" style={{ color: '#8E93A4' }}>
              已选 {selectedRowKeys.length} 项
            </span>
            <Splitter />
            {true && (
              <Button
                style={{ color: '#fff' }}
                type="text"
                onClick={() => {
                  onRefresh(selectedRowKeys);
                }}
              >
                重试
              </Button>
            )}

            {true && (
              <Button
                style={{ color: '#fff' }}
                type="text"
                onClick={() => {
                  onStop(selectedRowKeys);
                }}
              >
                暂停
              </Button>
            )}

            <Button
              style={{ color: '#fff' }}
              type="text"
              onClick={() => {
                if (selectedItems.length === 0) return;
                onDelete(selectedItems, true);
                setSelectedRowKeys([]);
                setShowDel(false);
                // onDelete(selectedRowKeys);
              }}
            >
              删除
            </Button>
          </Space>
        </div>
      )}
    </>
  );
}
